package com.demo.jdkproxy;

import org.apache.log4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by chenhe17596 on 2017/6/24.
 * 汽车行驶时间代理类
 */
public class CarTimeProxy implements InvocationHandler {

    Object object;
    Logger logger = Logger.getLogger(this.getClass());
    public CarTimeProxy(Object object){
        this.object=object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        logger.debug("当前代理类:"+object.getClass().getName()+",代理方法:"+method.getName()+",参数:"+array2String(args));

        long beginTime = System.currentTimeMillis();
        System.out.println("汽车开始行驶...");
        Object obj = method.invoke(object,args);
        long endTime = System.currentTimeMillis();
        System.out.println("汽车行驶结束... 耗时：" + (endTime-beginTime) + " 毫秒");
        return obj;
    }

    private String array2String(Object[] args){

        if (null == args){
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0 ;i < args.length; i++){
            stringBuilder.append(args[i]+"->"+args[i].getClass().getName()+",");
        }
        if (stringBuilder.lastIndexOf(",")!=-1){
            return stringBuilder.substring(0,stringBuilder.length()-1);
        }
        return stringBuilder.toString();
    }
}
